package cn.java75.sp.conf;

import cn.java75.sp.entity.Admin;
import cn.java75.sp.entity.LoginUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author oldliu
 * @since 1.0
 */
///@Component
public class TokenCheckFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        System.out.println(">>>>>当前请求了>>>>>>>>>>>>>>"+httpServletRequest.getServletPath()+", 时间："+System.nanoTime());
        String token = httpServletRequest.getHeader("token");

        LoginUser admin=null;
        try {
//            ValueOperations<String, String> operation = redisTemplate.opsForValue();
           ValueOperations<String, LoginUser> operation = redisTemplate.opsForValue();
            admin=operation.get(token);
//            String add = operation.get(token);
//            ObjectMapper mapper=new ObjectMapper();
//            admin = mapper.readValue(add, LoginUser.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (admin != null &&( authentication==null || authentication.getPrincipal() == null)) {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(admin, null, admin.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

}
